import { ModernBaseService } from '../service/base/ModernBaseService';
import { EquipTemplate } from '../core/manage/EquipManage';
import { quality } from '../shared/face/enums';

/**
 * 装备仓储类 - 负责装备模板的数据访问与缓存
 */
export class EquipRepository extends ModernBaseService {
    private equipTemplates: Map<string, EquipTemplate> = new Map();
    private initialized = false;

    constructor(container?: any) {
        super(container);
    }

    /**
     * 初始化装备模板数据
     */
    async initialize(): Promise<void> {
        if (this.initialized) {
            return;
        }

        try {
            this.log('正在初始化装备模板...');
            const templates = await this.sdk.db.find('equip_templates');
            
            if (templates.length) {
                this.equipTemplates.clear();
                templates.forEach((template: any) => {
                    this.equipTemplates.set(template.id, template);
                });
                this.log(`从数据库加载了 ${templates.length} 个装备模板`);
            } else {
                // 创建默认装备模板
                await this.createDefaultTemplate();
            }
            
            this.initialized = true;
            this.log(`装备模板初始化完成，共 ${this.equipTemplates.size} 个模板`);
        } catch (error) {
            this.log('装备模板初始化失败: ' + (error as any).message, 'error');
            throw error;
        }
    }

    /**
     * 创建默认装备模板
     */
    private async createDefaultTemplate(): Promise<void> {
        try {
            const Counter = require('../core/manage/Counter').default;
            const { CounterKey } = require('../core/manage/Counter');
            const gameCfg = require('../../gameCfg').default;

            const defaultTemplate: EquipTemplate = {
                uuid: this.sdk.tool.common.uuid,
                strengthenLevel: 1,
                count: 1,
                id: Counter.get(CounterKey.装备ID),
                name: '默认装备',
                desc: '默认装备',
                sys: '魔幻本质',
                type: '修真',
                job: '剑修',
                solt_type: '法宝',
                attribute: [],
                skill: [],
                creator: 'sys',
                emoji: "🗡️",
                icon: gameCfg.defaultIcon,
                quality: {
                    min: quality.D,
                    max: quality.SSR
                },
                source: "",
                createTime: Date.now(),
                updateTime: Date.now()
            };
            
            // 保存到内存和数据库
            await this.saveTemplate(defaultTemplate);
            this.log('创建默认装备模板成功');
        } catch (error) {
            this.log('创建默认装备模板失败: ' + (error as any).message, 'error');
            throw error;
        }
    }

    /**
     * 保存装备模板到数据库
     */
    async saveTemplate(template: EquipTemplate): Promise<string> {
        this.validateRequiredParams({ template }, ['template']);
        
        try {
            // 确保模板有ID和时间戳
            if (!template.id) {
                const Counter = require('../core/manage/Counter').default;
                const { CounterKey } = require('../core/manage/Counter');
                template.id = Counter.get(CounterKey.装备ID);
            }
            
            const now = Date.now();
            template.updateTime = now;
            if (!template.createTime) {
                template.createTime = now;
            }

            // 保存到数据库
            await this.sdk.db.insert('equip_templates', template);
            
            // 更新内存缓存
            this.equipTemplates.set(template.id, template);
            
            this.log(`装备模板保存成功: ${template.name} (ID: ${template.id})`);
            return template.id;
        } catch (error) {
            this.log('保存装备模板失败: ' + (error as any).message, 'error');
            throw error;
        }
    }

    /**
     * 根据ID获取装备模板
     */
    async getTemplateById(id: string): Promise<EquipTemplate | undefined> {
        await this.ensureInitializedAsync();
        this.validateRequiredParams({ id }, ['id']);
        
        const template = this.equipTemplates.get(id);
        if (template) {
            this.log(`获取装备模板: ${template.name} (ID: ${id})`);
        } else {
            this.log(`装备模板不存在: ${id}`, 'warn');
        }
        
        return template;
    }

    /**
     * 获取所有装备模板
     */
    async getAllTemplates(): Promise<EquipTemplate[]> {
        await this.ensureInitializedAsync();
        
        const templates = Array.from(this.equipTemplates.values());
        this.log(`获取所有装备模板，共 ${templates.length} 个`);
        
        return templates;
    }

    /**
     * 获取随机装备模板ID
     */
    async getRandomTemplateId(): Promise<string> {
        const templates = await this.getAllTemplates();
        
        if (templates.length === 0) {
            this.log('没有可用的装备模板', 'warn');
            return '';
        }
        
        const randomIndex = Math.floor(Math.random() * templates.length);
        const templateId = templates[randomIndex].id;
        
        this.log(`随机获取装备模板ID: ${templateId}`);
        return templateId;
    }

    /**
     * 获取随机装备模板
     */
    async getRandomTemplate(): Promise<EquipTemplate | undefined> {
        const templates = await this.getAllTemplates();
        
        if (templates.length === 0) {
            this.log('没有可用的装备模板', 'warn');
            return undefined;
        }
        
        const randomIndex = Math.floor(Math.random() * templates.length);
        const template = templates[randomIndex];
        
        this.log(`随机获取装备模板: ${template.name} (ID: ${template.id})`);
        return template;
    }

    /**
     * 删除装备模板
     */
    async deleteTemplate(templateId: string): Promise<boolean> {
        await this.ensureInitializedAsync();
        this.validateRequiredParams({ templateId }, ['templateId']);
        
        try {
            const template = this.equipTemplates.get(templateId);
            if (!template) {
                this.log(`装备模板不存在: ${templateId}`, 'error');
                return false;
            }

            // 从数据库删除
            await this.sdk.db.remove('equip_templates', { id: templateId });
            
            // 从内存缓存删除
            this.equipTemplates.delete(templateId);
            
            this.log(`装备模板删除成功: ${templateId}`);
            return true;
        } catch (error) {
            this.log('删除装备模板失败: ' + (error as any).message, 'error');
            return false;
        }
    }

    /**
     * 更新装备模板
     */
    async updateTemplate(templateId: string, updates: Partial<EquipTemplate>): Promise<boolean> {
        await this.ensureInitializedAsync();
        this.validateRequiredParams({ templateId, updates }, ['templateId', 'updates']);
        
        try {
            const existingTemplate = this.equipTemplates.get(templateId);
            if (!existingTemplate) {
                this.log(`装备模板不存在: ${templateId}`, 'error');
                return false;
            }

            // 合并更新
            const updatedTemplate: EquipTemplate = {
                ...existingTemplate,
                ...updates,
                id: templateId, // 确保ID不变
                updateTime: Date.now()
            };

            // 更新数据库
            await this.sdk.db.update('equip_templates', { id: templateId }, updatedTemplate);
            
            // 更新内存缓存
            this.equipTemplates.set(templateId, updatedTemplate);
            
            this.log(`装备模板更新成功: ${templateId}`);
            return true;
        } catch (error) {
            this.log('更新装备模板失败: ' + (error as any).message, 'error');
            return false;
        }
    }

    /**
     * 按条件搜索装备模板
     */
    async searchTemplates(criteria: {
        sys?: string;
        type?: string;
        job?: string;
        solt_type?: string;
        creator?: string;
        qualityMin?: quality;
        qualityMax?: quality;
    }): Promise<EquipTemplate[]> {
        await this.ensureInitializedAsync();
        
        const allTemplates = Array.from(this.equipTemplates.values());
        
        const filtered = allTemplates.filter(template => {
            if (criteria.sys && template.sys !== criteria.sys) return false;
            if (criteria.type && template.type !== criteria.type) return false;
            if (criteria.job && template.job !== criteria.job) return false;
            if (criteria.solt_type && template.solt_type !== criteria.solt_type) return false;
            if (criteria.creator && template.creator !== criteria.creator) return false;
            if (criteria.qualityMin !== undefined && template.quality.min < criteria.qualityMin) return false;
            if (criteria.qualityMax !== undefined && template.quality.max > criteria.qualityMax) return false;
            
            return true;
        });
        
        this.log(`装备模板搜索结果: ${filtered.length} 个模板符合条件`);
        return filtered;
    }

    /**
     * 确保已初始化（异步版本）
     */
    private async ensureInitializedAsync(): Promise<void> {
        if (!this.initialized) {
            await this.initialize();
        }
    }

    /**
     * 获取模板统计信息
     */
    async getTemplateStats(): Promise<{
        total: number;
        bySys: Record<string, number>;
        byType: Record<string, number>;
        byJob: Record<string, number>;
        byCreator: Record<string, number>;
    }> {
        await this.ensureInitializedAsync();
        
        const templates = Array.from(this.equipTemplates.values());
        const stats = {
            total: templates.length,
            bySys: {} as Record<string, number>,
            byType: {} as Record<string, number>,
            byJob: {} as Record<string, number>,
            byCreator: {} as Record<string, number>
        };

        templates.forEach(template => {
            // 按系统统计
            stats.bySys[template.sys] = (stats.bySys[template.sys] || 0) + 1;
            
            // 按类型统计
            stats.byType[template.type] = (stats.byType[template.type] || 0) + 1;
            
            // 按职业统计
            stats.byJob[template.job] = (stats.byJob[template.job] || 0) + 1;
            
            // 按创建者统计
            stats.byCreator[template.creator] = (stats.byCreator[template.creator] || 0) + 1;
        });

        this.log('装备模板统计信息已生成');
        return stats;
    }
}